package com.coollang.smartbra.presenter;

import com.coollang.smartbra.activity.SportStatisticsActivity1;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.http.HttpCallBack;
import com.coollang.smartbra.http.MyHttp;
import com.coollang.smartbra.model.SportRecordModel;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.Urls;
import com.google.gson.Gson;

import java.util.Iterator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: Timmy
 * @data: 2018/1/30
 * @Fuction:
 */

public class SportStatisticsActivity1Presenter {

    private final long mRegisterTime;
    private SportStatisticsActivity1 mStatisticsActivity;

    public SportStatisticsActivity1Presenter(SportStatisticsActivity1 statisticsActivity1) {
        mStatisticsActivity = statisticsActivity1;
        String register_day = MyApplication.mLogInDataBean.getRegister_time();
        mRegisterTime = Long.parseLong(register_day);
    }

    /**
     * 获取历史数据
     *
     * @param actionCode
     */
    public void loadHistoryData(int actionCode) {
        MyHttp.getInstance().getSportRecord(actionCode, 1, getHistoryCallback);
    }

    private HttpCallBack getHistoryCallback = new HttpCallBack() {
        @Override
        public void onSuccess(String results, Call call, Response response) {
            SportRecordModel sportRecordModel = new Gson().fromJson(results, SportRecordModel.class);
            int resultCode = sportRecordModel.getCode();
            if (resultCode == Urls.CODE_SUCCESS) {
                // 获取成功
                List<SportRecordModel.DataBean> data = sportRecordModel.getData();
                iteratorRemove(data);
                mStatisticsActivity.updateHistoryData(data);
            } else {
                mStatisticsActivity.loadDataFailed(sportRecordModel.getMessage());
            }
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            mStatisticsActivity.loadDataFailed("请检查当前网络");
        }
    };

    public void iteratorRemove(List<SportRecordModel.DataBean> list) {
        Iterator<SportRecordModel.DataBean> it = list.iterator();
        while (it.hasNext()) {
            SportRecordModel.DataBean next = it.next();
            if (TimeUtils.getLongTime(next.getDate()) < mRegisterTime) {
                it.remove();
            }
        }
    }
}
